All files / src/hooks useMediaUpload.ts

0% Statements 0/81
0% Branches 0/25
0% Functions 0/9
0% Lines 0/80

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176                                                                                                                                                                                                                                                                                                                                                               
'use client';
 
import { useState, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { apiService } from '@/services/api';
 
interface UploadProgress {
    loaded: number;
    total: number;
    percentage: number;
}
 
interface UploadResult {
    url: string;
    path?: string;
    filename: string;
    size: number;
}
 
interface UseMediaUploadReturn {
    uploadFile: (
        file: File,
        category: string,
        tmdbId?: number,
        title?: string
    ) => Promise<UploadResult>;
    progress: UploadProgress | null;
    isUploading: boolean;
    error: string | null;
    cancelUpload: () => void;
}
 
/**
 * Hook for uploading media files with progress tracking
 */
export function useMediaUpload(): UseMediaUploadReturn {
    const { t } = useTranslation();
    const [progress, setProgress] = useState<UploadProgress | null>(null);
    const [isUploading, setIsUploading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const abortControllerRef = useRef<AbortController | null>(null);
    const xhrRef = useRef<XMLHttpRequest | null>(null);
 
    const cancelUpload = useCallback(() => {
        if (xhrRef.current) {
            xhrRef.current.abort();
            xhrRef.current = null;
        }
        if (abortControllerRef.current) {
            abortControllerRef.current.abort();
            abortControllerRef.current = null;
        }
        setIsUploading(false);
        setProgress(null);
        setError(t('user.shows.status.cancelled'));
    }, [t]);
 
    const uploadFile = useCallback(
        async (
            file: File,
            category: string,
            tmdbId?: number,
            title?: string
        ): Promise<UploadResult> => {
            setIsUploading(true);
            setError(null);
            setProgress({ loaded: 0, total: file.size, percentage: 0 });
 
            return new Promise((resolve, reject) => {
                const formData = new FormData();
                formData.append('file', file);
                formData.append('category', category);
                if (tmdbId) {
                    formData.append('tmdb_id', tmdbId.toString());
                }
                if (title) {
                    formData.append('title', title);
                }
 
                const xhr = new XMLHttpRequest();
                xhrRef.current = xhr;
 
                // Progress tracking
                xhr.upload.addEventListener('progress', (event) => {
                    if (event.lengthComputable) {
                        const percentage = Math.round((event.loaded / event.total) * 100);
                        setProgress({
                            loaded: event.loaded,
                            total: event.total,
                            percentage});
                    }
                });
 
                xhr.addEventListener('load', () => {
                    setIsUploading(false);
                    xhrRef.current = null;
 
                    if (xhr.status >= 200 && xhr.status < 300) {
                        try {
                            const response = JSON.parse(xhr.responseText);
                            setProgress(null);
                            resolve(response);
                        } catch {
                            const message = t('common.serverError');
                            setError(message);
                            reject(new Error(message));
                        }
                    } else {
                        let errorMessage = t('common.serverError');
                        try {
                            const errorResponse = JSON.parse(xhr.responseText);
                            errorMessage = errorResponse.message || errorResponse.error || errorMessage;
                        } catch {
                            // Use default error message
                        }
                        setError(errorMessage);
                        reject(new Error(errorMessage));
                    }
                });
 
                xhr.addEventListener('error', () => {
                    setIsUploading(false);
                    xhrRef.current = null;
                    const message = t('common.networkErrorDescription');
                    setError(message);
                    reject(new Error(message));
                });
 
                xhr.addEventListener('abort', () => {
                    setIsUploading(false);
                    xhrRef.current = null;
                    const message = t('user.shows.status.cancelled');
                    setError(message);
                    reject(new Error(message));
                });
 
                // Get auth token
                const token = typeof window !== 'undefined'
                    ? localStorage.getItem('iptv_auth_token')
                    : null;
 
                // Build API URL
                const baseUrl = process.env.NEXT_PUBLIC_API_URL || '';
                const url = `${baseUrl}/api/admin/media/upload`;
 
                xhr.open('POST', url);
 
                if (token) {
                    xhr.setRequestHeader('Authorization', `Bearer ${token}`);
                }
 
                xhr.send(formData);
            });
        },
        [t]
    );
 
    return {
        uploadFile,
        progress,
        isUploading,
        error,
        cancelUpload};
}
 
/**
 * Format bytes to human readable string
 */
export function formatFileSize(bytes: number): string {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}